import { LockOutlined, MobileOutlined, UserOutlined } from '@ant-design/icons';
import { Alert, message, Tabs } from 'antd';
import React, { useState } from 'react';
import { ProFormCaptcha, ProFormCheckbox, ProFormText, LoginForm } from '@ant-design/pro-form';
import { history, useModel } from 'umi';
import Footer from '@/components/Footer';
import { captchaLogin, passwordLogin } from './api';

import styles from './index.less';
import type { LoginParams } from './type';
import storage from '@/utils/store';

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC = () => {
  const [userLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const { setInitialState } = useModel('@@initialState');

  const passwordHandle = async (values: LoginParams) => {
    const res = await passwordLogin(values);

    if (res.code === 200) {
      storage.setLocal('info', res.data);
      await setInitialState((s: any) => ({
        ...s,
        currentUser: res.data,
      }));
      message.success('登录成功');
      history.push('/welcome');
    } else {
      message.error(res.msg);
    }
  };

  const captchaHandle = async (values: LoginParams) => {
    const res = await captchaLogin(values);

    if (res.code === 200) {
      const data = {
        name: res.username,
        password: res.password,
      };
      storage.setLocal('info', data);
      await setInitialState((s: any) => ({
        ...s,
        currentUser: data,
      }));
      message.success('登录成功');
      history.push('/welcome');
    } else {
      message.error(res.msg);
    }
  };

  const handleSubmit = (values: LoginParams) => {
    if (type === 'account') {
      passwordHandle(values);
    } else if (type === 'mobile') {
      captchaHandle(values);
    }
  };

  const { status, type: loginType } = userLoginState;
  const items = [
    { label: '账户密码登录', key: 'account' },
    { label: '手机号登录', key: 'mobile' },
  ];

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm
          title="风险清单"
          subTitle={'风险清单'}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as LoginParams);
          }}
        >
          <Tabs activeKey={type} onChange={setType} items={items} />
          {status === 'error' && loginType === 'account' && (
            <LoginMessage content={'错误的用户名和密码'} />
          )}
          {type === 'account' && (
            <>
              <ProFormText
                name="account"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'请输入用户名'}
                rules={[
                  {
                    required: true,
                    message: '用户名是必填项！',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'请输入密码'}
                rules={[
                  {
                    required: true,
                    message: '密码是必填项！',
                  },
                ]}
              />
            </>
          )}

          {status === 'error' && loginType === 'mobile' && <LoginMessage content="验证码错误" />}
          {type === 'mobile' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined className={styles.prefixIcon} />,
                }}
                name="mobile"
                placeholder={'请输入手机号！'}
                rules={[
                  {
                    required: true,
                    message: '手机号是必填项！',
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: '不合法的手机号！',
                  },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                captchaProps={{
                  size: 'large',
                }}
                placeholder={'请输入验证码！'}
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} ${'秒后重新获取'}`;
                  }
                  return '获取验证码';
                }}
                name="captcha"
                rules={[
                  {
                    required: true,
                    message: '验证码是必填项！',
                  },
                ]}
                onGetCaptcha={async (mobile) => {
                  console.log(mobile);
                  message.success('获取验证码成功！验证码为：1234');
                }}
              />
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <ProFormCheckbox noStyle name="autoLogin">
              自动登录
            </ProFormCheckbox>
            <a
              style={{
                float: 'right',
              }}
            >
              忘记密码 ?
            </a>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};
export default Login;
